package com.fruit.service.rights.impl;

import com.fruit.mapper.rights.UserRightsMapper;
import com.fruit.pojo.goods.RightConfig;
import com.fruit.pojo.rights.UserGoodsRights;
import com.fruit.pojo.rights.UserGoodsRightsHarvest;
import com.fruit.pojo.rights.UserGoodsRightsPost;
import com.fruit.service.goods.GoodsManager;
import com.fruit.service.rights.UserRightsManager;
import com.fruit.util.DateUtil;
import com.fruit.util.ResultInfo;
import com.fruit.util.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class UserRightsService implements UserRightsManager {
    @Autowired
    private UserRightsMapper userRightsMapper;

    @Autowired
	private GoodsManager goodsManager;
    
    /**
     * 权益列表
     */
    @Override
    public List<UserGoodsRights> userTrees(Map<String, Object> pam) {
    	long a=System.currentTimeMillis();
    	log.info("进入时间：" + a/1000f + "秒");
    	log.info("开始权益列表service方法 userTrees，传入的参数 pam：" + pam);
    	List<Map<String, String>> unitList = goodsManager.getUnitNameByUnit();
    	Map<String, String> unit = new HashMap<String, String>();
    	Map<String, String> unitMap = new HashMap<String, String>();
    	if(unitList!=null){
    		for(int i=0;i<unitList.size();i++){
    			unitMap = unitList.get(i);
    			unit.put((String) unitMap.get("unit"), (String) unitMap.get("name"));
        	}
    	}
    	List<UserGoodsRights> userGoodsRightsList = userRightsMapper.fruitTreeList(pam);
    	if(userGoodsRightsList!=null && userGoodsRightsList.size()>0){
    		for(int i=0;i<userGoodsRightsList.size();i++){
    			UserGoodsRights userGoodsRights = userGoodsRightsList.get(i);
    			userGoodsRights.setUnitDesc(unit.get(userGoodsRights.getUnit()));
    			userGoodsRights.setHarvestUnitDesc(unit.get(userGoodsRights.getHarvestUnit()));
    			userGoodsRights.setGoodsName(userGoodsRights.getGoodsName() + "(共" + userGoodsRights.getNum() + userGoodsRights.getUnitDesc() + ")");
    			boolean isState = DateUtil.compareDate(userGoodsRights.getEndUseTime(),DateUtil.getTime());
    			if(isState){//如果 isState为true  说明截至使用时间大于当前系统时间 那么就不过期
    				userGoodsRights.setState("01");
    			}else{
    				userGoodsRights.setState("00");
    			}
        	}
    	}
    	log.info("结束权益列表service方法 userTrees，返回的值userGoodsRightsList" + userGoodsRightsList);
    	log.info("结束时间：" + (System.currentTimeMillis()-a)/1000f + "秒");
    	return userGoodsRightsList;
    }

    @Override
    public UserGoodsRights getUserGoodsRight(int id) {
    	List<Map<String, String>> unitList = goodsManager.getUnitNameByUnit();
    	Map<String, String> unit = new HashMap<String, String>();
    	Map<String, String> unitMap = new HashMap<String, String>();
    	if(unitList!=null){
    		for(int i=0;i<unitList.size();i++){
    			unitMap = unitList.get(i);
    			unit.put((String) unitMap.get("unit"), (String) unitMap.get("name"));
        	}
    	}
        UserGoodsRights rights = userRightsMapper.find(id);
        if (rights == null) {
            return null;
        }
        rights.setUserGoodsRightsHarvests(userRightsMapper.findUserGoodsRightsHarvest(id));
        rights.setUnitDesc(unit.get(rights.getUnit()));
        rights.setHarvestUnitDesc(unit.get(rights.getHarvestUnit()));
        rights.setEndUseTime(DateUtil.ChTime(rights.getEndUseTime()));
        return rights;
    }

    @Override
    public Map<String, Object> insertGoodsRight(List<UserGoodsRights> UGRights,String tradeId) {
    	Map<String, Object> resMap = new HashMap<String, Object>();
    	try{
    		int rightId = 0;
    		for(int j=0;j<UGRights.size();j++){
    			UserGoodsRights goodsRights = UGRights.get(j);
    			int num = userRightsMapper.insertGoodsRight(goodsRights);
    	    	List<UserGoodsRightsHarvest> ugthList = new ArrayList<UserGoodsRightsHarvest>();
    	    	String[] expectHarvest = goodsRights.getExpectHarvests().split(",");//产量
    	    	String[] expectHarvestTime =goodsRights.getExpectHarvestTimes().split(",");//预计产量时间
    	    	for(int i=0;i<expectHarvest.length;i++){
    	    		UserGoodsRightsHarvest urh = new UserGoodsRightsHarvest();
    	    		urh.setExpectHarvest(new BigDecimal(expectHarvest[i]));
    	    		urh.setExpectHarvestTime(expectHarvestTime[i]);
    	    		urh.setUserGoodsRightsId((int) goodsRights.getId());
    	    		ugthList.add(urh);
    	    	}
    	    	userRightsMapper.insertGoodsRightHarvest(ugthList);
    	    	rightId += num;
    		}
    		if(rightId!=UGRights.size()){//如果返回的行数和 list集合的个数相等 那么就说明 都插入进去啦
    			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "save_error", "新增失败!",null,ResultInfo.ROLLBACK));
    			return resMap;
    		}
    		resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "ok", "添加成功"));
    		return resMap;
    	}catch(Exception e){
    		e.printStackTrace();
    		resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception", "系统异常!",null,ResultInfo.ROLLBACK));
			return resMap;
    	}finally{
    		ResultInfo ri = (ResultInfo)resMap.get("result");
    		if(ResultInfo.ROLLBACK.equals(ri.getIsRollBack())){
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
    	}
        
    }
    
    @Override
	public List<UserGoodsRightsHarvest> findUserGoodsRightsHarvest(int id) {
    	List<UserGoodsRightsHarvest> ugList = userRightsMapper.findUserGoodsRightsHarvest(id);
    	if(ugList!=null && ugList.size()>0){
			for(UserGoodsRightsHarvest gst:ugList){
				gst.setExpectHarvestTime(DateUtil.ChTime(gst.getExpectHarvestTime()));
			}
		}
		return ugList;
	}

	@Override
	public List<UserGoodsRightsPost> findUserGoodsRightsPost(String type) {
		// TODO Auto-generated method stub
		return userRightsMapper.findUserGoodsRightsPost(type);
	}

	/**
	 * 我的权益首页
	 */
	@Override
	public List<RightConfig> getGoodsRightList(Map<String, Object> pam) {
		//获取所有的根分类
		List<RightConfig> rightConfigList = userRightsMapper.getClassId();
		if(rightConfigList!=null && rightConfigList.size()>0){
			//这个是用于判断查询 此用户下“所有”分类的数据 如果数据为空 则返回null 说明分类没有任何数据
			pam.put("classId",null);
			List<UserGoodsRights> userGoodsRightsList = userRightsMapper.getGoodsRightList(pam);
			if(userGoodsRightsList==null || userGoodsRightsList.size()==0){
				return null;
			}else{
				for(int i=0;i<rightConfigList.size();i++){
					RightConfig rcf = rightConfigList.get(i);
					pam.put("classId", goodsManager.getClassIdByPid(rcf.getClassId()));
					//查询此用户下“此”分类下面的所有的数据
					userGoodsRightsList = userRightsMapper.getGoodsRightList(pam);
					if(userGoodsRightsList!=null && userGoodsRightsList.size()>0){
						rcf.setUserGoodsRights(userGoodsRightsList);
					}
				}
			}
		}
		return rightConfigList;
	}

	/**
	 * 查询每个大类的统计百分比 
	 */
	public List<RightConfig> getClassPercentage(int userId) {
		List<RightConfig> rightConfigList = userRightsMapper.getClassPercentage(userId);
		int total=0;
		for(int i=0;i<rightConfigList.size();i++){
			RightConfig rightConfig = rightConfigList.get(i);
			if(rightConfig.getAlltotal()==0){
				rightConfig.setPercentage(0);
			}else{
				if(rightConfig.getTotal()==0){
					rightConfig.setPercentage(0);
				}else{
					if(i==rightConfigList.size()-1){//最后一个百分比肯定是最大的 （数据库根据百分比从小到大进行排序）
						if(total!=0){
							rightConfig.setPercentage(100-total);
						}
					}else{
						total=total+rightConfig.getPercentage();
					}
				}
			}
		}
		return rightConfigList;
	}

	@Override
	public int getRightNum(int userId) {
		Integer rightSum = userRightsMapper.getRightNum(userId);
		
		if(rightSum == null){
			return 0;
		}else{
			return rightSum;
		}
		
		 
	}
}
